package com.yibo.support.jwt;

import io.jsonwebtoken.*;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

/**
 * JWT认证工具 采用RSA加密处理
 *
 * @author zhanglei
 */
public class JWTUtils {

    /**
     * 私钥
     */
    private static RSAPrivateKey privateKey;

    /**
     * 公钥
     */
    private static RSAPublicKey publicKey;

    private static class SingletionJwt{
        private static final JWTUtils jwtutils = new JWTUtils();
    }

    public synchronized static JWTUtils getInstance(){
        if(privateKey == null || publicKey == null){
            privateKey = RSAUtils.getPrivateKey(RSAUtils.modules,RSAUtils.private_exponent);
            publicKey = RSAUtils.getPublicKey(RSAUtils.modules,RSAUtils.public_exponent);
        }
        return SingletionJwt.jwtutils;
    }


    /**
     * 通过用户ID  获取token
     * 默认token过期时间24小时
     *
     * @param userId  用户ID
     * @return  token
     */
    public String getToken(String userId){
        long  endTime = System.currentTimeMillis() + 60 * 1000  * 1440;
        return Jwts.builder().setSubject(userId).setExpiration(new Date(endTime))
                .signWith(SignatureAlgorithm.RS512,privateKey).compact();
    }


    /**
     * 获取token  设置失效时间  单位分钟
     *
     * @param userId  用户ID
     * @param exp   失效时间
     * @return      token
     */
    public String getToken(String userId,int exp){
        long endTime = System.currentTimeMillis() + 1000 * 60 * exp;
        return Jwts.builder().setSubject(userId).setExpiration(new Date(endTime))
                .signWith(SignatureAlgorithm.RS512,privateKey).compact();
    }


    public JWTResult  checkToken(String token){
        try {
            Claims claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody();
            String sub = claims.get("sub", String.class);
            return new JWTResult(true,"合法请求",sub,0);
        }catch (ExpiredJwtException e){
            return new JWTResult(false,"token已经过期",null,-101);
        }catch (SignatureException e){
            return new JWTResult(false,"token秘钥不正确",null,-102);
        }catch (Exception e){
            return new JWTResult(false,"token解析异常",null,103);
        }
    }

    public static class JWTResult{

        private boolean status;

        private String msg;

        private String userId;

        private int code;

        public JWTResult(){}

        public JWTResult(boolean status,String msg,String userId,int code){
            this.status = status;
            this.msg = msg;
            this.userId = userId;
            this.code = code;
        }

        public boolean isStatus() {
            return status;
        }

        public void setStatus(boolean status) {
            this.status = status;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }
    }

    public static void main(String[] args) {
        String token = getInstance().getToken("123");
        JWTResult result = getInstance().checkToken(token);
        System.out.println();
    }
}
